package com.blog.controller.blog;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.blog.commons.utils.IpUtil;
import com.blog.commons.web.base.BaseController;
import com.blog.commons.web.domain.response.PageResult;
import com.blog.commons.web.domain.response.Result;
import com.blog.pojo.TbBlog;
import com.blog.pojo.TbBlogComment;
import com.blog.pojo.TbBlogLog;
import com.blog.pojo.vo.BlogVO;
import com.blog.service.AdminService;
import com.blog.service.ArticleService;
import com.blog.service.CommentsService;
import com.blog.service.LogService;
import com.github.benmanes.caffeine.cache.Cache;
import eu.bitwalker.useragentutils.Browser;
import eu.bitwalker.useragentutils.OperatingSystem;
import eu.bitwalker.useragentutils.UserAgent;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ProjectName: springboot
 * @ClassName: BlogController
 * @Author: jian
 * @Description:
 * @Date: 2021/5/26 17:18
 * @Version: 1.0
 */
@Controller
@RequestMapping
public class BlogController {
    /**
     * 默认主题
     */
    private static String theme = "amaze";

    @Autowired
    private AdminService adminService;

    @Autowired
    private ArticleService articleService;

    @Autowired
    private CommentsService commentsService;

    //    @Autowired
//    private RedisTemplate redisTemplate;
    @Resource
    private Cache<String, Object> caffeineCache;

    @Resource
    private LogService logService;

    /**
     * 查询主题
     */
    public void getRedisTemplate() {
        String t = (String)caffeineCache.getIfPresent("theme");
        //String t = (String) redisTemplate.opsForValue().get("theme");
        if (StringUtils.isNotBlank(t)) {
            theme = t;
        }
    }

    @GetMapping({"", "/", "index"})
    public ModelAndView index(HttpServletRequest request) {
        this.getBrowserInfo(request);
        return this.page(1);
    }

    @GetMapping("page/{pageNum}")
    public ModelAndView page(@PathVariable("pageNum") Integer pageNum) {
        getRedisTemplate();
        Map<String, String> config = adminService.getWebSite();
        PageResult<BlogVO> result = articleService.getPageBlog(pageNum);
        ModelAndView mv = new ModelAndView();
        mv.setViewName("/blog/" + theme + "/index");
        mv.addObject("config", config);
        mv.addObject("copyRight", config.get("footerCopyRight"));
        mv.addObject("allBlog", result.getData());
        mv.addObject("page", result);
        mv.addObject("currentPage", pageNum);
        mv.addObject("hotBlog", articleService.getHotBlog());
        return mv;
    }

    /**
     * 组装返回数据
     *
     * @return
     */
    @PostMapping("getArticleList")
    @ResponseBody
    public Result getIndex() {
        List<BlogVO> allBlog = articleService.getAllBlog();
        return new Result(0, "成功", allBlog);
    }

    @GetMapping("toBlog/{id}")
    public ModelAndView toBlog(@PathVariable("id") Integer id, HttpServletRequest request,
                                HttpServletResponse response) throws ParseException {
        getRedisTemplate();
        ModelAndView mv = new ModelAndView();
        BlogVO tbBlog = articleService.getBlogById(id);
        List<TbBlogComment> comments = commentsService.list(id);
        if (null == tbBlog) {
            mv.setViewName("/error/404");
            return mv;
        }
        //更新观看人数
        articleService.updateBlogViews(id);
        mv.setViewName("/blog/" + theme + "/blog");
        mv.addObject("blog", tbBlog);
        mv.addObject("comments", comments);
        mv.addObject("config", adminService.getWebSite());
        return mv;
    }

    @GetMapping("getBlog/{id}")
    @ResponseBody
    public Result toBlog(@PathVariable("id") Integer id) {
        TbBlog tbBlog = articleService.findById(id);
        return new Result(0, "成功", tbBlog);
    }

    @GetMapping("s/{url}")
    public ModelAndView getPage(HttpServletRequest request, @PathVariable("url") String url) {
        getRedisTemplate();
        BlogVO tbBlog = articleService.getPageByUrl(url);
        Map<String, String> webSite = adminService.getWebSite();
        //更新观看人数
        articleService.updateBlogViews(tbBlog.getBlogId());
        ModelAndView mv = new ModelAndView();
        mv.setViewName("/blog/" + theme + "/blog");
        mv.addObject("blog", tbBlog);
        mv.addObject("config", webSite);
        return mv;
    }

    @GetMapping("article")
    public String toArticle() {
        return "/blog/" + theme + "/article";
    }

    @GetMapping("read")
    public String toRead() {
        return "/blog/" + theme + "/read";
    }

    /**
     * 首页归档数据返回
     *
     * @return
     */
    @GetMapping("archive")
    public ModelAndView archive() {
        ModelAndView mv = new ModelAndView();
        mv.addObject("blog", articleService.getArchiveBlog());
        mv.addObject("config", adminService.getWebSite());
        mv.setViewName("/blog/" + theme + "/archive");
        return mv;
    }

    public void getBrowserInfo(HttpServletRequest request) {
        String agent = request.getHeader("User-Agent");
//解析agent字符串
        UserAgent userAgent = UserAgent.parseUserAgentString(agent);
//获取浏览器对象
        Browser browser = userAgent.getBrowser();
//获取操作系统对象
        OperatingSystem operatingSystem = userAgent.getOperatingSystem();
        Map<String, Object> map = new HashMap<>();
        map.put("ip地址", IpUtil.getIpAddr(request));

        try {
            String json_result = IpUtil.getAddresses("183.242.37.114", "utf-8");
            map.put("访问地址",json_result);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        map.put("浏览器名", browser.getName());
        map.put("浏览器类型", browser.getBrowserType());
        map.put("浏览器家族", browser.getGroup());
        map.put("浏览器生产厂商", browser.getManufacturer());
        map.put("浏览器使用的渲染引擎", browser.getRenderingEngine());
        map.put("浏览器版本", userAgent.getBrowserVersion());
        map.put("操作系统名", operatingSystem.getName());
        map.put("访问设备类型", operatingSystem.getDeviceType());
        map.put("操作系统家族", operatingSystem.getGroup());
        map.put("操作系统生产厂商", operatingSystem.getManufacturer());

        logService.addLog(TbBlogLog.builder()
                .createTime(new Date())
                .operation("访问主页")
                .operationUser("默认用户")
                .type("1")
                .remark(JSONUtil.toJsonStr(map)).build());
    }

}
